#include "usermodel.hpp"
#include <iostream>
#include "database.hpp"

bool UserModel::Insert(User& user)
{
    char sql[1024] = {0};
    sprintf(sql, "insert into user(name, password, satate) values('%s', '%s', '%s')",\
            user.GetName().c_str(), user.GetPassword().c_str(), user.GetState().c_str());

    MySQL mysql;
    if (mysql.Connect()) {
        if (mysql.Update(sql)) {
            user.SetId(mysql_insert_id(mysql.GetConnection()));
            return true;
        }
    }
    return false;
}

User UserModel::Query(const int id)
{
    char sql[1024];
    sprintf(sql, "select * from user where id = %d", id);

    MySQL mysql;
    if (mysql.Connect()) {
        MYSQL_RES* res = mysql.Query(sql);
        if (res != nullptr) {
            MYSQL_ROW row = mysql_fetch_row(res);
            if (row != nullptr) {
                User user;
                user.SetId(atoi(row[0]));
                user.SetName(row[1]);
                user.SetPassword(row[2]);
                user.SetState(row[3]);
                mysql_free_result(res);
                return user;
            }
        }
    }
    return User();
}

bool UserModel::UpdateState(const User& user)
{
    char sql[1024];
    sprintf(sql, "update user set state = '%s' where id = %id", user.GetState().c_str(), user.GetId());

    MySQL mysql;
    if (mysql.Connect()) {
        if (mysql.Update(sql)) {
            return true;
        }
    }
    return false;
}

void UserModel::ResetState()
{
    char sql[1024] = "update user set state = 'offline' where state = 'online'";

    MySQL mysql;
    if (mysql.Connect()) {
        mysql.Update(sql);
    }
}